import { System } from 'cc';
import { sys } from 'cc';
import { js } from 'cc';
import { log } from 'cc';
import { director } from 'cc';
import { Eventify } from 'cc';
import { _decorator, Component, Node } from 'cc';
import { gm } from '../../managers/GameManager';
import { Observable } from '../../libs/rxjs/internal/Observable';
import { of } from '../../libs/rxjs/internal/observable/of';
const { ccclass, property } = _decorator;

@ccclass('WechatRecorderManager')
export class WechatRecorderManager extends Eventify(System) {

    public static instance: WechatRecorderManager;
    static ID = 'wechat_recorder_system';

    static registerSystem() {
        director.unregisterSystem(director.getSystem(WechatRecorderManager.ID));
        director.registerSystem(WechatRecorderManager.ID, wcrm, System.Priority.MEDIUM);
        wcrm.init();
    }

    init() {
        log(`<${js.getClassName(this)}>`, 'init');

        if (sys.platform == sys.Platform.WECHAT_GAME) {
            this.WeChatRecorderInit();
        }
    }

    private callBackBegin: any = null;       //开始录屏回调
    private callBackEnd: any = null;         //结束录屏回调
    private callBackErr: any = null;         //录屏失败回调
    private recorder: any = null;            //录屏组件

    //开始录屏
    private recorderBegin() {
        if (this.callBackBegin != null) {
            this.callBackBegin.call(this);
        }
    }
    //结束录屏
    private recorderEnd(res) {
        if (this.callBackEnd != null) {
            this.callBackEnd.call(this, res);
        }
    }
    //录屏失败
    private recorderErr() {
        if (this.callBackErr != null) {
            this.callBackErr.call(this);
        }
    }

    res: any = null;

    time: number = 0;
    recording: boolean = false;
    isError: boolean = false;

    alreadyStop: boolean = false;

    update(t) {
        if (this.recording) {
            this.time += t;
            if (this.time > 60) {
                this.stopRecoder(() => { });
                this.alreadyStop = true;
            }
        }
        // console.log('@alreadyStop', this.alreadyStop);
    }

    /**
     * 微信录屏组件
     */
    public WeChatRecorderInit() {
        console.log("微信录屏组件初始化");
        let self = this;

        if (sys.platform == sys.Platform.WECHAT_GAME) {
            this.recorder = globalThis.tt.getGameRecorderManager();

            //注册开始录屏事件
            this.recorder.onStart(function (res) {
                console.log("=========> 开始录屏：", res);
                self.recorderBegin();
            });
            //注册结束录屏事件
            this.recorder.onStop(function (res) {
                console.log("=========> 录屏结束：", res);
                this.alreadyStop = true;
                wcrm.res = res;
                self.recorderEnd(res);
            });
            //注册录屏错误事件
            this.recorder.onError(function (res) {
                console.log("=========> 录屏出错：", res);
                self.isError = true;
                self.recorderErr();
            });
        }
    }

    //开始录屏
    public startRecoder(callback) {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            let ts = 65;
            let frame = 24;

            if (sys.os == sys.OS.ANDROID) {
                ts = 65;
                frame = 24;
            } else if (sys.os == sys.OS.IOS) {
                ts = 65;
                frame = 15;
            }

            if (this.recorder != null) {
                this.callBackBegin = callback;

                this.alreadyStop = false;
                this.time = 0;
                this.recording = true;
                this.isError = false;

                this.recorder.start({
                    duration: ts,   //录屏时长300s
                    frameRate: frame,   //录屏帧率24
                });
            }
        } else {
            callback(true);
        }
    }

    //停止录屏
    public stopRecoder(callback) {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            if (this.alreadyStop) {
                callback(true);
            } else {
                if (this.recorder != null) {
                    this.callBackEnd = callback;
                    this.recorder.stop();
                    this.recording = false;
                    console.log('record time', this.time);
                }
            }
        } else {
            callback(true);
        }
    }

    public pauseRecorder() {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            this.recorder.pause();
            this.recording = false;
        }
    }

    public resumeRecorder() {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            this.recorder.resume();
            this.recording = true;
        }
    }

    sharing = false;
    public share() {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            if (this.sharing) {
                gm.frontTipShow('请稍候...', 1).subscribe();
            } else {
                return new Observable(observer => {
                    this.sharing = true;
                    globalThis.tt.shareAppMessage({
                        title: "小屋惊魂",
                        channel: "video",
                        extra: {
                            videoPath: wcrm.res.videoPath, //录屏后得到的文件地址
                            withVideoId: true,
                        },
                        success: (_r) => {
                            this.sharing = false;
                            globalThis.tt.showToast({
                                title: "分享成功",
                            });
                            observer.next(true);
                            observer.complete();
                        },
                        fail: (e) => {
                            this.sharing = false;
                            globalThis.tt.showToast({
                                title: "分享失败",
                                icon: 'fail'
                            });
                            observer.next(false);
                            observer.complete();
                        },
                    });
                });
            }
        } else {
            gm.frontTipShow('分享成功', 1).subscribe();
            return of(true);
        }
    }
}

globalThis.WechatRecorderManager = WechatRecorderManager;

export const wcrm = WechatRecorderManager.instance = new WechatRecorderManager();